import { useEffect, useRef, useState } from "react";
import { Flex, Progress } from 'antd';

interface SSEMessage {
    progress: number;
    status: "PROCESSING" | "COMPLETED" | "FAILED";
    message: string;
    taskId: string;
}

type SSEventProp = MessageEvent;

const SSEPage = () => {
    const [progress, setProgress] = useState(0);
    const [error, setError] = useState<string | null>(null);
    // 1. Declare EventSource variable
    const eventSourceRef = useRef<EventSource | null>(null);


    const startConnectSse = () => {
        try {
            // 2. initialize SSE connection
            eventSourceRef.current = new EventSource('http://localhost:1983/sse/task/1234');

            // 3. watch SSE message
            eventSourceRef.current.addEventListener("progressUpdate", (event: SSEventProp) => {
                try {
                    const parsedData: SSEMessage = JSON.parse(event.data);
                    if (typeof parsedData.progress === 'number') {
                        setProgress(parsedData.progress);
                    }
                    if (parsedData.status === 'COMPLETED' || parsedData.status === 'FAILED') {
                        eventSourceRef.current?.close();
                    }
                } catch (error) {
                    console.error('JSON Analyze:', error);
                    setError('JSON Analyze Error');
                    eventSourceRef.current?.close();
                }
            });

            // 4. Watch SSE connection error (key: check server connection)
            eventSourceRef.current.onerror = (err) => {
                console.error('SSE Connection Error:', err);
                setError('SSE Connection Failed, please check the server');
                eventSourceRef.current?.close();
            };

            // 5. Watch SSE connection open (optional: confirm connection success)
            eventSourceRef.current.onopen = () => {
                console.log('SSE Connection Successful');
                setError(null);
            };
        } catch (initErr) {
            console.error('SSE Initialization Failed:', initErr);
            setError('SSE Initialization Failed');
        }
    };
    useEffect(() => {
        startConnectSse();
        // 6. Close SSE connection when component unmount (avoid memory leak)
        return () => {
            eventSourceRef.current?.close();
            eventSourceRef.current = null;
            console.log('SSE Connection Closed');
        };
    }, []);

    const handleReconnect = () => {
        eventSourceRef.current?.close();
        setProgress(0);
        setError(null);
        startConnectSse();
    };

    const handleStopConnect = () => {
        eventSourceRef.current?.close();
    };

    return (
        <div>
            {error && <div style={{ color: 'red' }}>Error: {error}</div>}
            <h2>Current Progress: {progress}%</h2>
            {/* Optional: Add progress bar visualization */}
            {/* <div style={{ height: 20, width: '100%', border: '1px solid #ccc', marginTop: 10 }}>
                <div
                    style={{ height: '100%', width: `${progress}%`, backgroundColor: '#4CAF50' }}
                />
            </div> */}

            <Flex align="center" wrap gap={30}>
                <Progress type="circle" percent={progress} />
                <Progress type="circle" percent={progress} size="small" />
                <Progress type="circle" percent={progress} size={20} />
            </Flex>

            <Flex align="center" wrap gap={30}>
                <Progress type="dashboard" percent={progress} />
                <Progress type="dashboard" percent={progress} size="small" />
                <Progress type="dashboard" percent={progress} size={20} />
            </Flex>
            <Flex align="center" wrap gap={30}>
                <Progress steps={3} percent={progress} />
                <Progress steps={3} percent={progress} size="small" />
                <Progress steps={3} percent={progress} size={20} />
                <Progress steps={3} percent={progress} size={[20, 30]} />
            </Flex>

            <Flex gap="small" vertical>
                <Progress
                    percent={progress}
                    percentPosition={{ align: 'center', type: 'inner' }}
                    size={[200, 20]}
                    strokeColor="#E6F4FF"
                />
                <Progress percent={progress} percentPosition={{ align: 'center', type: 'inner' }} size={[300, 20]} />
                <Progress
                    percent={progress}
                    percentPosition={{ align: 'start', type: 'inner' }}
                    size={[300, 20]}
                    strokeColor="#B7EB8F"
                />
                <Progress
                    percent={progress}
                    percentPosition={{ align: 'end', type: 'inner' }}
                    size={[300, 20]}
                    strokeColor="#001342"
                />
                <Progress percent={progress} percentPosition={{ align: 'center', type: 'inner' }} size={[400, 20]} />
                <Progress percent={progress} percentPosition={{ align: 'start', type: 'outer' }} />
                <Progress percent={progress} percentPosition={{ align: 'start', type: 'outer' }} />
                <Progress percent={progress} percentPosition={{ align: 'center', type: 'outer' }} size="small" />
                <Progress percent={progress} percentPosition={{ align: 'center', type: 'outer' }} />
            </Flex>

            <div style={{ marginTop: '20px' }} className="mt-2 ">
                <button className="bg-blue-500 w-123 hover:bg-blue-700 text-blue-800 py-2 px-4 rounded border-b-blue-700" onClick={handleReconnect}>Reconnect</button>
            </div>
            <div style={{ marginTop: '20px' }} className="mt-2 ">
                <button className="bg-red-500 w-123 hover:bg-red-700 text-red-800 py-2 px-4 rounded border-b-red-700" onClick={handleStopConnect}>Stop</button>
            </div>
        </div>
    );
};

export default SSEPage;